<script setup lang="ts">

import {computed} from "vue";
import type {FormInstance} from "element-plus";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
})
const emit = defineEmits(['update:modelValue', 'success', 'edit'])

const visible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})
const isEdit = ref(false)

const title = computed(() => {
  return isEdit.value ? '编辑房型' : '添加房型'
})
const formRef = ref<FormInstance>()
const formData = ref({
  name: '',
  price: '',
  number: '',
  index: -1,
})

function resetForm() {
  formRef.value?.resetFields()
  formData.value = {
    name: '',
    price: '',
    number: '',
    index: -1,
  }
  isEdit.value = false
}


const formRules = computed(() => {
  return {
    name: [
      {
        required: true,
        message: '请输入房型名称',
        trigger: 'blur'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入房型价格',
        trigger: 'blur'
      }
    ],
    number: [
      {
        required: true,
        message: '请输入房型数量',
        trigger: 'blur'
      }
    ]
  }
})

function cancelHandle() {
  visible.value = false
}

function addHandle() {
  if (!isEdit.value) return emit('success', formData.value)
  editHandle(formData.value)
}

function editHandle(payload: any) {
  emit('edit', payload)
}

function confirmHandle() {
  formRef.value?.validate().then(() => addHandle()).catch(() => {
  })
}

function editItem(data: any, index: number) {
  isEdit.value = true
  const {name, price, number} = data
  formData.value = {
    name, price, number, index,
  }
}

defineExpose({
  editItem
})
</script>

<template>
  <el-dialog v-model="visible"
             width="400px"
             :title="title"
             @closed="resetForm"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules">
      <el-form-item label="房型名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入房型名称" type="text"/>
      </el-form-item>
      <el-form-item label="房型价格" prop="price">
        <el-input v-model="formData.price" placeholder="请输入房型价格" type="text"/>
      </el-form-item>
      <el-form-item label="房型数量" prop="number">
        <el-input v-model="formData.number" placeholder="请输入房型数量" type="number"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-space>
        <el-button type="info" plain @click="cancelHandle">取消</el-button>
        <el-button type="primary" plain @click="confirmHandle">确定</el-button>
      </el-space>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
